package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.*;
import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @SneakyThrows
    @Override
    public String fileupload(MultipartFile file){
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(minioConstantProperties.getEndpointUrl())
                        .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                        .build();
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder()
                                .bucket(minioConstantProperties.getBucketName())
                        .build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(minioConstantProperties.getBucketName())
                    .build());
        }
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file.getOriginalFilename();
        String fileExtName = FilenameUtils.getExtension(originalFilename);
        String fullFileName = fileName+"."+fileExtName;
        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(minioConstantProperties.getBucketName())
                        .object(fullFileName)
                        .stream(file.getInputStream(),file.getSize(),-1)
                        .contentType(file.getContentType())
                        .build());
        String url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fullFileName;
        return url;
    }
}
